package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.LoadDataManager;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.ui.AbstractSpinerAdapter.IOnItemSelectListener;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;

/**
 * 事故上传的信息填写界面，Created by Administrator on 2016/5/12.
 */
public class SingleAccidentLoadingView extends LFView implements View.OnClickListener, IOnItemSelectListener, ILSMsgListener {
    private String appCaseNo;//案件编号
    private Context context = null;
    private View view = null;
    private BaseApplication mApplication;
    private Dialog processDialog;
    private EntityBean[] DrivingLicenceBeans;//车辆信息
    private EntityBean myDrivingLiscenceBean;//驾驶证的bean
    private List<String> carnoList = null;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    private Button bt_singleaccidentloading;
    private Button bt_singleaccidentloading_record;
    private EditText et_singleaccidentloadingpic5;
    private EditText et_singleaccdentidcardme;
    private LinearLayout iv_loadingsingleaccident;
    private RelativeLayout rl_singlesingleaccidentloading;
    private EditText et_singleaccidentloadingpic4;
    private String myCarType;
    private String myCarFrameNo;
    private String myCarPic;
    private EditText phoneET;

    public SingleAccidentLoadingView(Context context, String appCaseNo, EntityBean myDrivingLiscenceBean) {
        super(context);
        this.context = context;
        this.appCaseNo = appCaseNo;
        this.mApplication = (BaseApplication) context.getApplicationContext();
        this.myDrivingLiscenceBean = myDrivingLiscenceBean;

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {
        checkBindingCarInfo();
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        initData();
    }

    //查询
    private void initData() {
        carnoList = new ArrayList<String>();
    }


    private void initView() {
        view = View.inflate(context, R.layout.view_accidentloadingsingle, null);
        bt_singleaccidentloading = (Button) view.findViewById(R.id.bt_singleaccidentloading);
        bt_singleaccidentloading_record = (Button) view.findViewById(R.id.bt_singleaccidentloading_record);
        et_singleaccidentloadingpic5 = (EditText) view.findViewById(R.id.et_singleaccidentloadingpic5);
        et_singleaccidentloadingpic4 = (EditText) view.findViewById(R.id.et_singleaccidentloadingpic4);
        et_singleaccdentidcardme = (EditText) view.findViewById(R.id.et_singleaccdentidcardme);//本方驾驶证号
        et_singleaccdentidcardme.setText(myDrivingLiscenceBean.getString("cardno"));
        et_singleaccidentloadingpic5.setText(myDrivingLiscenceBean.getString("carownername"));
        iv_loadingsingleaccident = (LinearLayout) view.findViewById(R.id.iv_loadingsingleaccident);
        rl_singlesingleaccidentloading = (RelativeLayout) view.findViewById(R.id.rl_singlesingleaccidentloading);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("事故上传");

        phoneET = (EditText)view.findViewById(R.id.et_singleaccdentidcardmetel);
        phoneET.setText(mApplication.getLoginInfo().getBean("userinfo").getString("mobilephone"));
    }

    private void regEvent(boolean b) {
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (null != bt_singleaccidentloading) {
            bt_singleaccidentloading.setOnClickListener(b ? this : null);
        }
        if (null != bt_singleaccidentloading_record) {
            bt_singleaccidentloading_record.setOnClickListener(b ? this : null);
        }
        if (null != iv_loadingsingleaccident) {
            iv_loadingsingleaccident.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hn_btn_back:
                closeForm();
                break;
            case R.id.bt_singleaccidentloading_record:
                BindCarView bindcarview = new BindCarView(context, null);
                FrameworkManager.getInstance().showNewForm(context, bindcarview);
                break;
            case R.id.iv_loadingsingleaccident:
                UiUtil.showSelectPopWindow(context, carnoList, this, rl_singlesingleaccidentloading, true);
                break;
            case R.id.bt_singleaccidentloading: //提交
                submitAccidentCase();
                break;
        }
    }

    @Override
    public void onItemClick(int pos, View view) {
        switch (view.getId()) {
            case R.id.rl_singlesingleaccidentloading:
                et_singleaccidentloadingpic4.setText(carnoList.get(pos));
                //cartypeString = carTypeList.get(pos);
                break;
            default:
                break;
        }
    }


    //根据用户id查询用户绑定的车辆信息
    private void checkBindingCarInfo() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean userInfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("userid", userInfo.get("id"));
        bean.set("username", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());

        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPSEARCHCARS, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            DrivingLicenceBeans = bean.getBeans("data");
                            if (null != DrivingLicenceBeans && DrivingLicenceBeans.length > 0) {
                                carnoList.clear();
                                for (EntityBean eBean : DrivingLicenceBeans) {
                                    carnoList.add(eBean
                                            .getString("carno"));
                                }
                            }
                        }
//                        else {
//                            UiUtil.showToast(context, redes);
//                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        }else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    @Override
    public Object onLSMsg(int arg0, Object... arg1) {
        if (arg0 == 99) {
            //绑定成功调取查询车辆
            checkBindingCarInfo();
        }
        return null;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        regEvent(false);
        removeILSMsgListener(this);
    }

    //事故上传
    private void submitAccidentCase() {
        String myCarNo = et_singleaccidentloadingpic4.getText().toString().trim();//车牌号
        if (TextUtils.isEmpty(myCarNo)){
            UiUtil.showToast(context,"请选择车牌号");
            return;
        }
        String phoneNumber = phoneET.getText().toString().trim();//手机号
        if (TextUtils.isEmpty(phoneNumber)){
            UiUtil.showToast(context,"请输入正确的手机号");
            return;
        }
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = mApplication.getKckpRequestBean();
        // caseno
        bean.set("appcaseno", appCaseNo);
        bean.set("casecarno", myCarNo);
        bean.set("appphone", phoneNumber);
        // 经度
        bean.set("caselon", mApplication.getLongitude());
        // 纬度
        bean.set("caselat", mApplication.getLatitude());
        // 地址
        bean.set("accidentplace", mApplication.getAddress());
        // 提交时间
        bean.set("sibmitdate", CommontUtils.getNowTime());
        //bean.set("areaid", userinfo.getString("areaid")); // 区域
        bean.set("areaid", mApplication.getAreaid()); // 调试数据
        bean.set("alarmtime", CommontUtils.getNowTime());
        bean.set("token", mApplication.getToken());
        bean.set("accidenttype", "");
        bean.set("accidentdes", "");
        bean.set("disposetype", "1");//增加一个自己还是交警定责的类型字段
        List<String> carTypeCode = getCarTypeCode(myCarNo);
        if (null != carTypeCode) {
            myCarType = carTypeCode.get(0);
            myCarFrameNo = carTypeCode.get(1);
            myCarPic = carTypeCode.get(2);
        }
        final EntityBean[] casecarlist = new EntityBean[1];//车主信息数组
        EntityBean bfBean = new EntityBean();// 本方数据
        String myName = et_singleaccidentloadingpic5.getText().toString().trim(); // 车主姓名
        bfBean.set("carownname", myName);
        bfBean.set("carownphone", phoneNumber); //手机号
        bfBean.set("driverlicence", et_singleaccdentidcardme.getText().toString().trim()); //
        bfBean.set("casecarno", et_singleaccidentloadingpic4.getText().toString().trim()); // 案件车牌号
        bfBean.set("cartype", myCarType); // 车型
        bfBean.set("frameno", myCarFrameNo);//车架号
        bfBean.set("cardno", et_singleaccdentidcardme.getText().toString().trim()); //身份证
        bfBean.set("driverfileno", myDrivingLiscenceBean.getString("driverfileno")); //档案编号
        bfBean.set("drivernoimg", myDrivingLiscenceBean.getString("drivernoimg")); //驾驶证照片
        bfBean.set("drivingnoimg", myCarPic);  //行驶证照片
        bfBean.set("dutytype", "0");  //单车默认全责
        casecarlist[0] = bfBean;

        bean.set("casecarlist", casecarlist);
        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.SUBMITCASEINFOR, bean,new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            UiUtil.showToast(context, "提交成功");
                            //单车提交后直接进入保险报案
                            InsuranceReportChoiceView iView = new InsuranceReportChoiceView(context, casecarlist, appCaseNo);
                            iView.setIfSingle("0");
                            FrameworkManager.getInstance().showNewForm(context, iView);
                        } else {
                            UiUtil.showToast(context, redes);
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        }else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                        return;
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    /**
     * 根据车牌获取获取车型，车架号，行驶证照片
     *
     * @param carNo
     * @return
     */
    private List<String> getCarTypeCode(String carNo) {
        if (TextUtils.isEmpty(carNo)) {
            return null;
        }
        List<String> myCarInfo = new ArrayList<String>();
        String value1 = "";
        String value2 = "";
        String value3 = "";
        for (EntityBean bean : DrivingLicenceBeans) {
            String getCarInfo = bean.getString("carno");
            if (carNo.equals(getCarInfo)) {
                value1 = bean.getString("cartype");//车型
                myCarInfo.add(value1);
                value2 = bean.getString("identificationnum");//车架号
                myCarInfo.add(value2);
                value3 = bean.getString("drivingnoimg");//行驶证照片
                myCarInfo.add(value3);
                break;
            }
        }
        return myCarInfo;
    }
}
